<template>
  <div>
    <van-nav-bar title="黑马头条" />
    <!-- 2. 表单登录 -->
    <van-form @submit="onSubmit" @failed="onFailed">
      <van-cell-group>
        <van-field
          label="手机号"
          v-model.trim="user.mobile"
          placeholder="请输入手机号"
          :rules="[{ pattern: /^1\d{10}$/, message: '请输入正确的手机号' }]"
        />
      </van-cell-group>
      <van-cell-group>
        <van-field
          label="密码"
          v-model.trim="user.code"
          type="text"
          placeholder="请输入密码"
          :rules="[{ pattern: /^\d{6}$/, message: '请输入正确的密码' }]"
        />
      </van-cell-group>
      <div style="margin: 16px" class="btn-wrap">
        <van-button
          class="van-button"
          round
          block
          type="info"
          native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// import { login } from '../../api/user'
export default {
  name: 'login',
  data () {
    return {
      user: {
        mobile: '13800000002', // 测试账号可以登录
        code: '246810' // 必须一定是这个值
      }
    }
  },
  methods: {
    async doLogin () {
      this.$toast({
        duration: 0, // 持续展示 toast,永远不会关闭
        overlay: true, // 整体添加一个遮罩
        message: '加载中...'
      })
      // 做具体的ajax提交动作
      try {
        this.$toast.loading({
          duration: 0, // 持续展示 toast,永远不会关闭
          overlay: true, // 整体添加一个遮罩
          message: '登录中...'
        })
        await this.$store.dispatch('userLogin', this.user)
        await this.$store.dispatch('user/getProfile')
        this.$toast.success('登录成功')
        // 页面跳转
        this.$router.push('/')
      } catch (err) {
        console.log(err)
        this.$toast.fail('登录不成功')
      }
    },
    onSubmit (values) {
      this.$toast.success('登录')
      this.doLogin()
    },
    onFailed () {
      console.log('验证失败')
    }
  }
}
</script>

<style lang="less" scoped>
// 按钮
.btn-wrap {
  padding: 20px;
  .van-button {
    width: 100%;
    background-color: #6db4fd;
    color: #fff;
  }
}
</style>
